package com.ruoyi.assemble.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * 运行命令行工具类
 * @author lee
 */
public class CommandUtils {

    private static final Logger logger = LoggerFactory.getLogger(CommandUtils.class);

    public static String run(String command) throws Exception {
        return run(new String[]{command});
    }

    public static String run(String[] command) throws Exception {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException("等待命令执行完成失败！！！");
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            //加上命令本身，打印出来
            result = Arrays.toString(command) + "\n" + result;
        } catch (Exception e){
            logger.error("errorMsg={}, command={}", e, Arrays.toString(command));
            throw new RuntimeException("command run is error!!!");
        }finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    public static synchronized Long getPidOfProcess(Process p) {
        Long pid = null;
        String s = "java.lang.UNIXProcess";
        try {
            if (p.getClass().getName().equals(s)) {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                pid = f.getLong(p);
                f.setAccessible(false);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return pid;
    }

}
